package com.gsafety.wellsfort.controller.organization;

import com.gsafety.wellsfort.common.context.LoginContextUtil;
import com.gsafety.wellsfort.common.util.ApiResponse;
import com.gsafety.wellsfort.common.util.ExcelUtil;
import com.gsafety.wellsfort.common.util.ResultCode;
import com.gsafety.wellsfort.domain.dto.ids.OrganizationDto;
import com.gsafety.wellsfort.domain.dto.ids.SchoolIdDTO;
import com.gsafety.wellsfort.domain.dto.school.SchoolDTO;
import com.gsafety.wellsfort.domain.model.organization.School;
import com.gsafety.wellsfort.domain.vo.PublishRangeTreeVO;
import com.gsafety.wellsfort.domain.vo.SchoolResultVO;
import com.gsafety.wellsfort.service.common.CityService;
import com.gsafety.wellsfort.service.organization.ISchoolService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * @Author: wuming
 * @Date: 2020/5/1 下午3:33
 * @Description
 */
@Slf4j
@RestController
@RequestMapping("/api/school")
@Api(value = "学校管理", description = "学校管理接口")
public class SchoolController {

    @Autowired
    private CityService cityService;

    @Autowired
    ISchoolService schoolService;

    @ApiOperation(value = "获取学校详情")
    @PostMapping(value = "/detail")
    public ApiResponse<School> getDetail(@RequestBody SchoolIdDTO idDto) {
        log.info("获取详情参数={}", idDto);
        return schoolService.getSchoolDetail(idDto.getSchoolId());
    }

    @ApiOperation(value = "获取学校列表,APP端使用以及后台查询所有学校列表时使用.若后台需要获取包含平台的学校列表,需要自己添加id=1为平台学校,接口不返回")
    @PostMapping(value = "/list")
    public ApiResponse<List<SchoolResultVO>> list(@RequestBody SchoolDTO schoolDTO) {
        return schoolService.list(schoolDTO);
    }

    @ApiOperation(value = "获取学校列表,后台学校列表专用,包含了不同角色查询数据权限列表")
    @PostMapping(value = "/getAll")
    public ApiResponse<List<School>> getSchoolList(@RequestBody SchoolDTO schoolDTO) {
        log.info("获取学校列表请求参数={}", schoolDTO);
        return schoolService.getAll(schoolDTO);
    }

    @ApiOperation(value = "添加学校")
    @PostMapping(value = "/add")
    public ApiResponse addSchool(@RequestBody School school) {
        if (school.getProvinceId() == null) {
            return ApiResponse.error(ResultCode.ERROR.getCode(), "学校省份id不能为空");
        }

        if (school.getCityId() == null) {
            return ApiResponse.error(ResultCode.ERROR.getCode(), "学校所处城市不能为空");
        }

        if (school.getCountyId() == null) {
            return ApiResponse.error(ResultCode.ERROR.getCode(), "学校所处县id不能为空");
        }
        school.setProvinceName(cityService.getCityNameByCode(school.getProvinceId()));
        school.setCityName(cityService.getCityNameByCode(school.getCityId()));
        school.setCountyName(cityService.getCityNameByCode(school.getCountyId()));
        if (!Optional.ofNullable(school).isPresent()) {
            return ApiResponse.error(ResultCode.ERROR.getCode(), "请求参数不能为空");
        }
        return schoolService.addSchool(school);
    }

    @ApiOperation(value = "学校编辑")
    @PostMapping(value = "/update")
    public ApiResponse updateSchool(@RequestBody School school) {
        school.setOperator(LoginContextUtil.getUserName());
        school.setModified(new Date());
        if (!Optional.ofNullable(school).isPresent()) {
            return ApiResponse.error(ResultCode.ERROR.getCode(), "请求参数不能为空");
        }
        return schoolService.update(school);
    }

    /**
     * 学校批量添加
     *
     * @param file
     * @return
     */
    @ApiOperation(value = "批量添加学校")
    @RequestMapping(value = "/batchAdd", method = RequestMethod.POST)
    public ApiResponse batchAdd(@RequestParam("fileName") MultipartFile file) {
        try {
            // 获取文件名
            String fileName = file.getOriginalFilename();
            // 获取文件后缀
            String prefix = fileName.substring(fileName.lastIndexOf("."));
            // 用uuid作为文件名，防止生成的临时文件重复
            final File excelFile = File.createTempFile(UUID.randomUUID().toString(), prefix);
            // MultipartFile to File
            file.transferTo(excelFile);
            List<School> list = ExcelUtil.getDtoList(excelFile, School.class);
            // 程序结束时，删除临时文件
            deleteFile(excelFile);
            return schoolService.batchAddSchool(list);
        } catch (Exception e) {
            log.error("exception={}", e);
            return ApiResponse.error(ResultCode.ERROR.getCode(), e.getMessage());
        }
    }


    /**
     * 获取权限
     *
     * @return
     */
    @ApiOperation(value = "获取学校组织")
    @PostMapping("/getOrganization")
    public ApiResponse<PublishRangeTreeVO> getOrganization(@RequestBody OrganizationDto organizationDto) {
        return schoolService.getOrganization(organizationDto);
    }


    /**
     * 获取权限
     *
     * @return
     */
    @ApiOperation(value = "获取默认学校组织,不需要回显数据")
    @PostMapping("/getDefaultOrganization")
    public ApiResponse<PublishRangeTreeVO> getDefaultOrganization() {
        return schoolService.getDefaultOrganization();
    }

    /**
     * 删除
     *
     * @param files
     */
    private void deleteFile(File... files) {
        for (File file : files) {
            if (file.exists()) {
                file.delete();
            }
        }
    }
}
